<template>
  <view class="zmt-editor-container">
    <!-- 工具栏 -->
    <view class="toolbar">
      <view class="toolbar-group">
        <button class="toolbar-btn" @click="execCommand('undo')" title="撤销11">
          <i class="icon-chexiao3 iconfont"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('redo')" title="重做">
          <i class="icon-zhongzuo3 iconfont"></i>
        </button>
      </view>
      
      <view class="toolbar-group">
        <button class="toolbar-btn" @click="execCommand('bold')" title="粗体">
          <i class="icon-cuti1 iconfont" style="font-size:22px;"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('italic')" title="斜体">
         <i class="icon-xieti2 iconfont"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('underline')" title="下划线">
          <i class="icon-xiahuaxian2 iconfont"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('strikethrough')" title="删除线">
          <i class="icon-shanchuxian2 iconfont"></i>
        </button>
      </view>
      
      <view class="toolbar-group">
        <button class="toolbar-btn" @click="execCommand('justifyleft')" title="左对齐">
         <i class="icon-zuoduiqi3 iconfont"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('justifycenter')" title="居中对齐">
         <i class="icon-juzhongduiqi1 iconfont"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('justifyright')" title="右对齐">
          <i class="icon-youduiqi2 iconfont"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('justifyfull')" title="两端对齐">
          <i class="icon-zuoyouduiqi iconfont"></i>
        </button>
      </view>
      
      <view class="toolbar-group">
        <button class="toolbar-btn" @click="execCommand('insertunorderedlist')" title="无序列表">
           <i class="icon-youxuliebiao1 iconfont"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('insertorderedlist')" title="有序列表">
          <i class="icon-youxuliebiao2 iconfont"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('indent')" title="增加缩进">
           <i class="icon-zengjiasuojinliang iconfont" style="font-size:22px;"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('outdent')" title="减少缩进">
           <i class="icon-Outdent iconfont"></i>
        </button>
      </view>
      
      <view class="toolbar-group">
        <!-- 修改：将view改为button -->
        <button class="toolbar-btn" @click="toggleColorPicker" title="字体颜色">
          <i class="icon-jurassic_font-color iconfont"></i>
          <view class="color-preview" :style="{ backgroundColor: currentTextColor || '#000' }"></view>
        </button>
        <!-- 颜色选择面板 -->
        <view class="color-picker" v-if="showColorPicker" @click.stop>
          <view class="color-grid">
            <view 
              v-for="color in colorPalette" 
              :key="color" 
              :style="{ backgroundColor: color }" 
              class="color-item" 
              @click="applyTextColor(color)"
            ></view>
          </view>
        </view>
        
        <view class="toolbar-select">
          <select @change="execCommand('fontSize', $event.target.value)">
            <option value="">字号</option>
            <option value="1">极小</option>
            <option value="2">小</option>
            <option value="3">正常</option>
            <option value="4">大</option>
            <option value="5">较大</option>
            <option value="6">很大</option>
            <option value="7">极大</option>
          </select>
        </view>
      </view>
      
      <view class="toolbar-group">
        <button class="toolbar-btn" @click="execCommand('insertimage')" title="插入图片">
          <i class="icon-charutupian3 iconfont"></i>
        </button>
        <!-- <button class="toolbar-btn" @click="execCommand('createlink')" title="插入链接">
         <i class="icon-charulianjie8 iconfont"></i>
        </button> -->
        <button class="toolbar-btn" @click="showTableDialog = true" title="插入入表格">
          <i class="icon-charubiaoge-copy-copy iconfont"></i>
        </button>
        <button class="toolbar-btn" @click="execCommand('blockquote')" title="引用">
          <i class="icon-yinyong- iconfont"></i>
        </button>
      </view>
      
      <view class="toolbar-group">
        <button class="toolbar-btn" @click="execCommand('removeformat')" title="清除格式">
          <i class="icon-qingchugeshi3 iconfont"></i>
        </button>
       <!-- <button class="toolbar-btn" @click="execCommand('fullscreen')" title="全屏屏编辑">
          <i class="icon-quanpingbianji6 iconfont"></i>
        </button> -->
      </view>
    </view>
    
    <!-- 编辑器区域 -->
    <view class="editor-content" ref="editorContent" contenteditable="true" @input="onContentChange"></view>
    
    <!-- 状态区域 -->
    <view class="status-bar">
      <text class="word-count">字数: {{ wordCount }}</text>
      <view class="upload-progress" v-if="uploading">
        <text>上传中: {{ uploadProgress }}%</text>
        <view class="progress-bar">
          <view class="progress-inner" :style="{ width: uploadProgress + '%' }"></view>
        </view>
      </view>
    </view>
    
    <!-- 图片上传提示 -->
    <view class="upload-tip" v-if="showUploadTip">
      <text>图片上传成功!</text>
      <button class="close-tip" @click="showUploadTip = false">
        <i class="fa fa-times"></i>
      </button>
    </view>
    
    <!-- 链接插入对话框 -->
    <view class="dialog" v-if="showLinkDialog">
      <view class="dialog-content">
        <text class="dialog-title">插入链接</text>
        <view class="dialog-body">
          <input type="text" placeholder="链接文本" v-model="linkText" class="no-focus-border" />
          <input type="text" placeholder="URL地址" v-model="linkUrl" class="no-focus-border" />
        </view>
        <view class="dialog-footer">
          <button class="dialog-btn cancel" @click="showLinkDialog = false">取消</button>
          <button class="dialog-btn confirm" @click="insertLink">确定</button>
        </view>
      </view>
    </view>
    
    <!-- 表格插入对话框 -->
    <view class="dialog" v-if="showTableDialog">
      <view class="dialog-content">
        <text class="dialog-title">插入表格</text>
        <view class="dialog-body">
          <input type="number" placeholder="行数" v-model="tableRows" min="1" max="10" class="no-focus-border" />
          <input type="number" placeholder="列数" v-model="tableCols" min="1" max="10" class="no-focus-border" />
        </view>
        <view class="dialog-footer">
          <button class="dialog-btn cancel" @click="showTableDialog = false">取消</button>
          <button class="dialog-btn confirm" @click="insertTable">确定</button>
        </view>
      </view>
    </view>
    
    <!-- 图片调整控制框 -->
    <view 
      v-if="resizingImage" 
      class="image-resize-handler" 
      :style="{ 
        width: resizingImage.width + 'px', 
        height: resizingImage.height + 'px',
        left: resizingImage.left + 'px',
        top: resizingImage.top + 'px'
      }"
    >
      <!-- 8个调整点 -->
      <view class="resize-handle top-left" @mousedown.stop="startResize('top-left')"></view>
      <view class="resize-handle top-center" @mousedown.stop="startResize('top-center')"></view>
      <view class="resize-handle top-right" @mousedown.stop="startResize('top-right')"></view>
      <view class="resize-handle middle-left" @mousedown.stop="startResize('middle-left')"></view>
      <view class="resize-handle middle-right" @mousedown.stop="startResize('middle-right')"></view>
      <view class="resize-handle bottom-left" @mousedown.stop="startResize('bottom-left')"></view>
      <view class="resize-handle bottom-center" @mousedown.stop="startResize('bottom-center')"></view>
      <view class="resize-handle bottom-right" @mousedown.stop="startResize('bottom-right')"></view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'zmt-editor',
  props: {
    // 初始内容
    initialContent: {
      type: String,
      default: ''
    },
    // 云存储配置
    cloudStorageConfig: {
      type: Object,
      default() {
        return {
          uploadUrl: '', // 上传URL
          fileKey: 'file', // 文件字段名
          successHandler: null, // 自定义成功处理函数
          failHandler: null, // 自定义失败处理函数
          headers: {} // 请求头
        }
      }
    }
  },
  watch:{
	 "initialContent"(val){
		 this.$refs.editorContent.$el.innerHTML = val;
		 this.$emit('contentChange', this.getContent());
		 this.updateWordCount();
	 } 
  },
  data() {
    return {
      wordCount: 0,
      uploading: false,
      uploadProgress: 0,
      showUploadTip: false,
      showLinkDialog: false,
      linkText: '',
      linkUrl: '',
      isFullscreen: false,
      showTableDialog: false,
      tableRows: 3,
      tableCols: 3,
      showColorPicker: false,
      currentTextColor: '',
      colorPalette: [
        '#000000', '#424242', '#636363', '#9E9E9E', '#BDBDBD', '#FFFFFF',
        '#FFEBEE', '#FFCDD2', '#EF9A9A', '#E57373', '#EF5350', '#F44336',
        '#D32F2F', '#B71C1C', '#FF8A80', '#FF5252', '#FF1744', '#D50000',
        '#FCE4EC', '#F8BBD0', '#F48FB1', '#F06292', '#EC407A', '#E91E63',
        '#D81B60', '#C2185B', '#FF80AB', '#FF4081', '#F50057', '#C51162',
        '#F3E5F5', '#E1BEE7', '#CE93D8', '#BA68C8', '#AB47BC', '#9C27B0',
        '#8E24AA', '#7B1FA2', '#EA80FC', '#E040FB', '#D500F9', '#AA00FF',
        '#E8EAF6', '#C5CAE9', '#9FA8DA', '#7986CB', '#5C6BC0', '#3F51B5',
        '#3949AB', '#303F9F', '#8C9EFF', '#536DFE', '#3D5AFE', '#304FFE',
        '#E3F2FD', '#BBDEFB', '#90CAF9', '#64B5F6', '#42A5F5', '#2196F3',
        '#1E88E5', '#1976D2', '#82B1FF', '#448AFF', '#2979FF', '#2962FF',
        '#E0F7FA', '#B2EBF2', '#80DEEA', '#4DD0E1', '#26C6DA', '#00BCD4',
        '#00ACC1', '#0097A7', '#84FFFF', '#18FFFF', '#00E5FF', '#00B8D4',
        '#E0F2F1', '#B2DFDB', '#80CBC4', '#4DB6AC', '#26A69A', '#009688',
        '#00897B', '#00796B', '#A7FFEB', '#64FFDA', '#1DE9B6', '#00BFA5',
        '#E8F5E9', '#C8E6C9', '#A5D6A7', '#81C784', '#66BB6A', '#4CAF50',
        '#43A047', '#388E3C', '#B9F6CA', '#69F0AE', '#00E676', '#00C853',
        '#F1F8E9', '#DCEDC8', '#C5E1A5', '#AED581', '#9CCC65', '#8BC34A',
        '#7CB342', '#689F38', '#CCFF90', '#B2FF59', '#76FF03', '#64DD17',
        '#FFFDE7', '#FFF9C4', '#FFF59D', '#FFF176', '#FFEE58', '#FFEB3B',
        '#FDD835', '#FBC02D', '#FFFF8D', '#FFFF00', '#FFEA00', '#FFD600',
        '#FFF8E1', '#FFECB3', '#FFE082', '#FFD54F', '#FFCA28', '#FFC107',
        '#FFB300', '#FFA000', '#FFE57F', '#FFD740', '#FFC400', '#FFAB00',
        '#FFF3E0', '#FFE0B2', '#FFCC80', '#FFB74D', '#FFA726', '#FF9800',
        '#FB8C00', '#F57C00', '#FFD180', '#FFAB40', '#FF9100', '#FF6D00',
        '#FBE9E7', '#FFCCBC', '#FFAB91', '#FF8A65', '#FF7043', '#FF5722',
        '#F4511E', '#E64A19', '#FF9E80', '#FF6E40', '#FF3D00', '#DD2C00',
        '#EFEBE9', '#D7CCC8', '#BCAAA4', '#A1887F', '#8D6E63', '#795548',
        '#6D4C41', '#5D4037', '#D7CCC8', '#BCAAA4', '#8D6E63', '#5D4037',
        '#ECEFF1', '#CFD8DC', '#B0BEC5', '#90A4AE', '#78909C', '#607D8B',
        '#546E7A', '#455A64', '#B0BEC5', '#90A4AE', '#78909C', '#455A64',
      ],
      // 图片调整相关数据
      resizing: false,
      resizingImage: null,
      activeResizeHandle: null,
      originalImage: null,
      startX: 0,
      startY: 0,
      aspectRatio: 1
    }
  },
  mounted() {
    // 设置初始内容
    this.$refs.editorContent.innerHTML = this.initialContent;
    // 计算初始字数
    this.updateWordCount();
    // 初始化编辑器
    setTimeout(() => {
      this.initEditor();
    }, 0);
    
    // 点击其他区域关闭颜色选择器
    document.addEventListener('click', this.closeColorPicker);
    
    // 添加图片和表格调整功能
    //this.$refs.editorContent.addEventListener('mousedown', this.handleMouseDown);
    document.addEventListener('mousemove', this.handleMouseMove);
    document.addEventListener('mouseup', this.handleMouseUp);
    
    // 监听编辑器内容变化，处理图片选择状态
    document.addEventListener('selectionchange', this.handleSelectionChange);
  },
  beforeDestroy() {
    // 移除事件监听
    if (this.$refs.editorContent) {
      this.$refs.editorContent.removeEventListener('paste', this.handlePaste);
      this.$refs.editorContent.removeEventListener('mousedown', this.handleMouseDown);
    }
    document.removeEventListener('mousemove', this.handleMouseMove);
    document.removeEventListener('mouseup', this.handleMouseUp);
    document.removeEventListener('click', this.closeColorPicker);
    document.removeEventListener('selectionchange', this.handleSelectionChange);
  },
  methods: {
    // 初始化编辑器
    initEditor() {
      // 修复：添加this.$refs.editorContent的存在检查
      if (!this.$refs.editorContent) {
        console.error('无法获取编辑器元素引用');
        return;
      }
      
      // 设置编辑器样式
      this.$refs.editorContent.style.minHeight = '200px';
      this.$refs.editorContent.style.padding = '15px';
      this.$refs.editorContent.style.backgroundColor = '#fff';
      this.$refs.editorContent.style.border = '1px solid #ddd';
      this.$refs.editorContent.style.borderRadius = '4px';
      this.$refs.editorContent.style.fontFamily = 'Microsoft YaHei,微软雅黑,Arial, sans-serif';
      this.$refs.editorContent.style.fontSize = '16px';
      this.$refs.editorContent.style.lineHeight = '1.6';
      this.$refs.editorContent.style.outline = 'none'; // 确保内联样式也移除了outline
      
      // 监听粘贴事件，处理图片上传
      this.$refs.editorContent.addEventListener('paste', this.handlePaste);
      
      // 监听内容变化事件
      this.$refs.editorContent.addEventListener('input', this.onContentChange);
      this.$refs.editorContent.addEventListener('keyup', this.updateWordCount);
      this.$refs.editorContent.addEventListener('keydown', this.updateWordCount);
      
      // 启用图片调整大小功能
      document.execCommand('enableObjectResizing', false, true);
      
      // 添加表格和图片调整大小支持
      this.$refs.editorContent.contentEditable = true;
      this.$refs.editorContent.designMode = 'on';
      
      // 确保编辑器获得焦点
      this.$refs.editorContent.focus();
    },
    
    // 执行编辑器命令
    execCommand(command, value = null) {
      if (command === 'insertimage') {
        this.chooseImage();
        return;
      }
      
      if (command === 'createlink') {
        this.showLinkDialog = true;
        return;
      }
      
      if (command === 'fullscreen') {
        this.toggleFullscreen();
        return;
      }
      
      // 特殊处理颜色命令
      if (command === 'foreColor') {
        document.execCommand('foreColor', false, value);
        this.currentTextColor = value;
      } else {
        document.execCommand(command, false, value);
      }
      
      // 修改：使用原生DOM方法获取焦点
      if (this.$refs.editorContent && this.$refs.editorContent.$el) {
        this.$refs.editorContent.$el.focus();
      } else if (this.$refs.editorContent) {
        this.$refs.editorContent.focus();
      }
      
      this.updateWordCount();
      this.$emit('contentChange', this.getContent()); // 确保执行命令后触发内容变化事件
    },
    
    // 切换颜色选择器显示状态
    toggleColorPicker(event) {
      // 阻止事件冒泡，防止触发document的click事件关闭颜色选择器
      event.stopPropagation();
      this.showColorPicker = !this.showColorPicker;
      
      // 计算颜色选择器的位置
      if (this.showColorPicker) {
        const buttonRect = event.currentTarget.getBoundingClientRect();
        const colorPicker = this.$el.querySelector('.color-picker');
        
        if (colorPicker) {
          // 设置颜色选择器的位置
          colorPicker.style.top = `${buttonRect.bottom + window.scrollY + 5}px`;
          colorPicker.style.left = `${buttonRect.left + window.scrollX}px`;
        }
      }
    },
    
    // 关闭颜色选择器
    closeColorPicker(event) {
      // 如果点击的元素不是颜色选择器的子元素，也不是触发颜色选择器的按钮，则关闭颜色选择器
      const colorPicker = this.$el.querySelector('.color-picker');
      const colorButton = this.$el.querySelector('.toolbar-btn[title="字体颜色"]');
      
      if (colorPicker && 
          !colorPicker.contains(event.target) && 
          (!colorButton || !colorButton.contains(event.target))) {
        this.showColorPicker = false;
      }
    },
    
    // 应用文本颜色
    applyTextColor(color) {
      this.execCommand('foreColor', color);
      // 延迟关闭，确保颜色应用成功
      setTimeout(() => {
        this.showColorPicker = false;
      }, 100);
    },
    
    // 选择图片上传
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          this.uploadImage(res.tempFilePaths[0], res.tempFiles[0].name);
        }
      });
    },
    
    // 使用uniCloud.uploadFile上传图片到uniCloud
    uploadImage(filePath, fileName) {
		var that = this;
      this.uploading = true;
      this.uploadProgress = 0;
      
      // 获取文件扩展名
      const fileExt = this.getExtension(fileName);
      
      // 生成云存储文件名（使用时间戳确保唯一性）
      const cloudPath = `${fileExt}`;
      const newFileName = new Date().getTime() + '.' + fileExt;
      uniCloud.uploadFile({
        filePath: filePath,
        cloudPath: newFileName,
		onUploadProgress: function(progressEvent) {
		          that.uploadProgress = Math.round(
		            (progressEvent.loaded * 100) / progressEvent.total
		          );
		        },
        success: (res) => {
          
          if (res.fileID) {
            // 成功获取fileID，将其作为图片URL插入编辑器
            this.insertImage(res.fileID);
            this.showUploadTip = true;
            
            // 3秒后隐藏提示
            setTimeout(() => {
              this.showUploadTip = false;
            }, 3000);
          } else {
            uni.showToast({
              title: '图片上传失败，无法获取fileID',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('图片上传失败', err);
          uni.showToast({
            title: '图片上传失败: ' + err.errMsg,
            icon: 'none'
          });
        },
        complete: () => {
          this.uploading = false;
        }
      });
    },
    
    //获取文件扩展名
    getExtension(filename) {
      const lastDot = filename.lastIndexOf('.');
      return lastDot === -1 ? '' : filename.substring(lastDot + 1);
    },
    
    // 插入图片到编辑器
    insertImage(imageUrl) {
      // 修改：移除内联样式中的固定宽度，让图片可以自由调整大小
      const imgHtml = `<img src="${imageUrl}" style="height:auto;max-width:500px;cursor:move;" contenteditable="true" draggable="true" data-image-id="${Date.now()}" />`;
      document.execCommand('insertHTML', false, imgHtml);
      
      // 修改：使用原生DOM方法获取焦点
      if (this.$refs.editorContent && this.$refs.editorContent.$el) {
        this.$refs.editorContent.$el.focus();
      } else if (this.$refs.editorContent) {
        this.$refs.editorContent.focus();
      }
      
      this.updateWordCount();
      this.$emit('contentChange', this.getContent());
    },
    
    // 插入链接
    insertLink() {
      if (!this.linkUrl) {
        uni.showToast({
          title: '请输入URL地址',
          icon: 'none'
        });
        return;
      }
      
      const linkText = this.linkText || this.linkUrl;
      const linkHtml = `<a href="${this.linkUrl}" target="_blank">${linkText}</a>`;
      
      document.execCommand('insertHTML', false, linkHtml);
      
      // 修改：使用原生DOM方法获取焦点
      if (this.$refs.editorContent && this.$refs.editorContent.$el) {
        this.$refs.editorContent.$el.focus();
      } else if (this.$refs.editorContent) {
        this.$refs.editorContent.focus();
      }
      
      this.updateWordCount();
      this.$emit('contentChange', this.getContent());
      
      // 重置链接对话框
      this.linkText = '';
      this.linkUrl = '';
      this.showLinkDialog = false;
    },
    
    // 插入表格
    insertTable() {
      const rows = parseInt(this.tableRows) || 3;
      const cols = parseInt(this.tableCols) || 3;
      
      // 创建表格HTML
      let tableHtml = '<table border="1" style="border-collapse:collapse;width:100%;table-layout:fixed;"><tbody>';
      
      // 添加表头行
      tableHtml += '<tr>';
      for (let j = 0; j < cols; j++) {
        tableHtml += `<th style="padding:8px;text-align:center;position:relative;">表头${j + 1}<div class="resize-handle" data-col="${j}"></div></th>`;
      }
      tableHtml += '</tr>';
      
      // 添加数据行
      for (let i = 0; i < rows - 1; i++) {
        tableHtml += '<tr>';
        for (let j = 0; j < cols; j++) {
          tableHtml += `<td style="padding:8px;position:relative;"><div class="resize-handle" data-col="${j}"></div></td>`;
        }
        tableHtml += '</tr>';
      }
      
      tableHtml += '</tbody></table>';
      
	  console.log('table',tableHtml);
      // 插入表格
      document.execCommand('insertHTML', true, tableHtml);
      
      // 修改：使用原生DOM方法获取焦点
      if (this.$refs.editorContent && this.$refs.editorContent.$el) {
        this.$refs.editorContent.$el.focus();
      } else if (this.$refs.editorContent) {
        this.$refs.editorContent.focus();
      }
      
      this.updateWordCount();
      this.$emit('contentChange', this.getContent());
      
      // 重置表格对话框
      this.tableRows = 3;
      this.tableCols = 3;
      this.showTableDialog = false;
    },
    
    // 处理粘贴事件
    handlePaste(e) {
      // 阻止默认粘贴行为
      e.preventDefault();
      
      // 获取粘贴的文本
      const text = (e.originalEvent || e).clipboardData.getData('text/plain');
      
      // 获取粘贴的图片
      const items = (e.originalEvent || e).clipboardData.items;
      if (items) {
        for (let i = 0; i < items.length; i++) {
          if (items[i].type.indexOf('image') !== -1) {
            const blob = items[i].getAsFile();
            const reader = new FileReader();
            
            reader.onloadend = () => {
              // 将图片转换为Base64格式并上传
              this.uploadBase64Image(reader.result);
            };
            
            reader.readAsDataURL(blob);
            return;
          }
        }
      }
      
      // 如果没有图片，则插入纯文本
      document.execCommand('insertText', false, text);
      this.updateWordCount();
      this.$emit('contentChange', this.getContent());
    },
    
    // 切换全屏编辑模式
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen;
      
      const editorContainer = this.$refs.editorContent;
      const body = document.body;
      
      if (this.isFullscreen) {
        // 进入全屏
        if (editorContainer.requestFullscreen) {
          editorContainer.requestFullscreen();
        } else if (editorContainer.mozRequestFullScreen) {
          editorContainer.mozRequestFullScreen();
        } else if (editorContainer.webkitRequestFullscreen) {
          editorContainer.webkitRequestFullscreen();
        } else if (editorContainer.msRequestFullscreen) {
          editorContainer.msRequestFullscreen();
        }
        
        // 修改样式
        body.classList.add('fullscreen-mode');
      } else {
        // 退出全屏
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
        
        // 恢复样式
        body.classList.remove('fullscreen-mode');
      }
    },
    
    // 内容变化处理
    onContentChange(e) {
      this.updateWordCount();
      this.$emit('contentChange', this.getContent());
    },
    
    // 更新字数统计
    updateWordCount() {
      // 修复：添加条件检查，确保editorContent存在且有innerText属性
      if (this.$refs.editorContent && typeof this.$refs.editorContent.$el.innerHTML === 'string') {
        // 使用文本内容而非HTML长度，更准确地统计字数
        const content = this.$refs.editorContent.$el.innerHTML;
        // 移除空白字符，只计算实际字符数
        const cleanContent = content.replace(/<[^>]*>/g, '').replace(/\s/g, '');
        this.wordCount = cleanContent.length;
      } else {
        this.wordCount = 0;
      }
    },
    
    // 获取编辑器内容
    getContent() {
      try {
        // 修改：使用原生DOM方法获取内容
        if (this.$refs.editorContent && this.$refs.editorContent.$el) {
          return this.$refs.editorContent.$el.innerHTML;
        } else if (this.$refs.editorContent) {
          return this.$refs.editorContent.innerHTML;
        }
        return '';
      } catch (error) {
        console.error('获取编辑器内容时出错:', error);
        return '';
      }
    },
    
    // 设置编辑器内容
    setContent(htmlContent) {
      try {
        if (this.$refs.editorContent && this.$refs.editorContent.$el) {
          this.$refs.editorContent.$el.innerHTML = htmlContent;
        } else if (this.$refs.editorContent) {
          this.$refs.editorContent.innerHTML = htmlContent;
        }
        this.updateWordCount();
        this.$emit('contentChange', this.getContent());
      } catch (error) {
        console.error('设置编辑器内容时出错:', error);
      }
    },
    
    // 表格单元格大小调整相关方法
    handleMouseDown(e) {
      // 检查是否点击了表格列的调整手柄
      const resizeHandle = e.target.closest('.resize-handle');
      if (resizeHandle) {
        e.preventDefault();
        e.stopPropagation();
        
        // 获取当前列和表格
        this.resizing = true;
        this.resizeCol = parseInt(resizeHandle.dataset.col);
        this.resizeTable = resizeHandle.closest('table');
        
        // 获取初始位置和宽度
        this.startX = e.clientX;
        this.colWidth = this.resizeTable.rows[0].cells[this.resizeCol].offsetWidth;
        
        // 添加调整时的样式
        document.body.style.cursor = 'col-resize';
        return;
      }
      
      // 检查是否点击了图片
      const img = e.target.closest('img');
      if (img && this.$refs.editorContent.contains(img)) {
        e.preventDefault();
        e.stopPropagation();
        
        // 计算图片位置和尺寸
        const rect = img.getBoundingClientRect();
        const editorRect = this.$refs.editorContent.getBoundingClientRect();
        
        this.resizingImage = {
          element: img,
          width: rect.width,
          height: rect.height,
          left: rect.left - editorRect.left,
          top: rect.top - editorRect.top,
          originalWidth: rect.width,
          originalHeight: rect.height
        };
        
        // 存储原始图片数据用于调整
        this.originalImage = {
          width: rect.width,
          height: rect.height,
          left: rect.left - editorRect.left,
          top: rect.top - editorRect.top
        };
        
        // 计算宽高比
        this.aspectRatio = rect.width / rect.height;
      } else {
        // 如果点击的不是图片，隐藏调整框
        this.resizingImage = null;
      }
    },
    
    handleMouseMove(e) {
      if (this.resizing && this.resizeTable) {
        e.preventDefault();
        
        // 计算宽度变化
        const diffX = e.clientX - this.startX;
        const newWidth = Math.max(50, this.colWidth + diffX); // 最小宽度为50px
        
        // 设置所有行的对应列宽度
        for (let i = 0; i < this.resizeTable.rows.length; i++) {
          this.resizeTable.rows[i].cells[this.resizeCol].style.width = `${newWidth}px`;
        }
        
        // 更新内容变化
        this.$emit('contentChange', this.getContent());
      }
      
      // 处理图片调整
      if (this.resizingImage && this.activeResizeHandle) {
        e.preventDefault();
        
        const editorRect = this.$refs.editorContent.getBoundingClientRect();
        const imgRect = this.resizingImage.element.getBoundingClientRect();
        
        // 计算鼠标移动距离
        const deltaX = e.clientX - this.startX;
        const deltaY = e.clientY - this.startY;
        
        // 根据不同的调整点计算新的宽高
        let newWidth, newHeight, newLeft, newTop;
        
        switch (this.activeResizeHandle) {
          case 'top-left':
            newWidth = this.originalImage.width - deltaX;
            newHeight = this.aspectRatio ? newWidth / this.aspectRatio : this.originalImage.height - deltaY;
            newLeft = this.originalImage.left + deltaX;
            newTop = this.originalImage.top + deltaY;
            break;
            
          case 'top-center':
            newHeight = this.originalImage.height - deltaY;
            newWidth = this.aspectRatio ? newHeight * this.aspectRatio : this.originalImage.width;
            newTop = this.originalImage.top + deltaY;
            newLeft = this.originalImage.left;
            break;
            
          case 'top-right':
            newWidth = this.originalImage.width + deltaX;
            newHeight = this.aspectRatio ? newWidth / this.aspectRatio : this.originalImage.height - deltaY;
            newTop = this.originalImage.top + deltaY;
            newLeft = this.originalImage.left;
            break;
            
          case 'middle-left':
            newWidth = this.originalImage.width - deltaX;
            newHeight = this.aspectRatio ? newWidth / this.aspectRatio : this.originalImage.height;
            newLeft = this.originalImage.left + deltaX;
            newTop = this.originalImage.top;
            break;
            
          case 'middle-right':
            newWidth = this.originalImage.width + deltaX;
            newHeight = this.aspectRatio ? newWidth / this.aspectRatio : this.originalImage.height;
            newLeft = this.originalImage.left;
            newTop = this.originalImage.top;
            break;
            
          case 'bottom-left':
            newWidth = this.originalImage.width - deltaX;
            newHeight = this.aspectRatio ? newWidth / this.aspectRatio : this.originalImage.height + deltaY;
            newLeft = this.originalImage.left + deltaX;
            newTop = this.originalImage.top;
            break;
            
          case 'bottom-center':
            newHeight = this.originalImage.height + deltaY;
            newWidth = this.aspectRatio ? newHeight * this.aspectRatio : this.originalImage.width;
            newTop = this.originalImage.top;
            newLeft = this.originalImage.left;
            break;
            
          case 'bottom-right':
            newWidth = this.originalImage.width + deltaX;
            newHeight = this.aspectRatio ? newWidth / this.aspectRatio : this.originalImage.height + deltaY;
            newLeft = this.originalImage.left;
            newTop = this.originalImage.top;
            break;
        }
        
        // 确保最小尺寸
        const minSize = 50;
        if (newWidth >= minSize && newHeight >= minSize) {
          // 更新调整框位置和大小
          this.resizingImage.width = newWidth;
          this.resizingImage.height = newHeight;
          this.resizingImage.left = newLeft;
          this.resizingImage.top = newTop;
          
          // 更新实际图片尺寸
          this.resizingImage.element.style.width = `${newWidth}px`;
          this.resizingImage.element.style.height = `${newHeight}px`;
          
          // 更新内容变化
          this.$emit('contentChange', this.getContent());
        }
      }
    },
    
    handleMouseUp(e) {
      if (this.resizing) {
        this.resizing = false;
        this.resizeTable = null;
        this.resizeCol = null;
        document.body.style.cursor = '';
      }
      
      // 结束图片调整
      if (this.activeResizeHandle) {
        this.activeResizeHandle = null;
        document.body.style.cursor = '';
      }
    },
    
    // 开始图片调整
    startResize(handleType) {
      if (!this.resizingImage) return;
      
      this.activeResizeHandle = handleType;
      this.startX = event.clientX;
      this.startY = event.clientY;
      
      // 设置调整时的鼠标样式
      switch (handleType) {
        case 'top-left':
        case 'bottom-right':
          document.body.style.cursor = 'nwse-resize';
          break;
        case 'top-right':
        case 'bottom-left':
          document.body.style.cursor = 'nesw-resize';
          break;
        case 'top-center':
        case 'bottom-center':
          document.body.style.cursor = 'ns-resize';
          break;
        case 'middle-left':
        case 'middle-right':
          document.body.style.cursor = 'ew-resize';
          break;
      }
    },
    
    // 处理编辑器中的选择变化
    handleSelectionChange() {
      const selection = window.getSelection();
      
      // 如果没有选择内容，隐藏调整框
      if (selection.rangeCount === 0) {
        this.resizingImage = null;
        return;
      }
      
      const range = selection.getRangeAt(0);
      const commonAncestor = range.commonAncestorContainer;
      
      // 如果选择的内容不在编辑器内，隐藏调整框
      // if (!this.$refs.editorContent.contains(commonAncestor)) {
      //   this.resizingImage = null;
      //   return;
      // }
      
      // 检查是否选中了图片
      const img = commonAncestor.closest ? commonAncestor.closest('img') : null;
      
      if (img && this.$refs.editorContent.contains(img)) {
        // 计算图片位置和尺寸
        const rect = img.getBoundingClientRect();
        const editorRect = this.$refs.editorContent.getBoundingClientRect();
        
        this.resizingImage = {
          element: img,
          width: rect.width,
          height: rect.height,
          left: rect.left - editorRect.left,
          top: rect.top - editorRect.top,
          originalWidth: rect.width,
          originalHeight: rect.height
        };
        
        // 计算宽高比
        this.aspectRatio = rect.width / rect.height;
      } else {
        // 如果选中的不是图片，隐藏调整框
        this.resizingImage = null;
      }
    }
  }
}
</script>

<style scoped>
@import url('//at.alicdn.com/t/c/font_4928612_o9rdcbljzr.css');

/* 配置Tailwind自定义颜色和工具类 */
@layer utilities {
  .content-auto {
    content-visibility: auto;
  }
  
  .focus-none {
    @apply focus:border-0 focus:ring-0 focus:outline-none;
  }

  .focus-border-gray-400 {
    @apply focus:border-gray-400;
  }

  .no-focus-border {
    @apply focus:border-0 focus:ring-0;
  }
}

.zmt-editor-container {
  width: 100%;
  background-color: #f8f9fa;
  border-radius: 6px;
  overflow: hidden;
  border:1px solid #eee;
  box-shadow: 1px 2px 8px 0 rgb(0 0 0 / 10%);
}

.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  padding: 8px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.toolbar-group {
  display: flex;
  margin-right: 10px;
  margin-bottom: 5px;
}

.toolbar-btn {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background-color: transparent;
  border-radius: 4px;
  cursor: pointer;
  margin: 0 2px;
  transition: all 0.2s;
  background:#f8f8f8;
}

.toolbar-btn:hover {
  background-color: #f0f0f0;
}

.toolbar-btn:active {
  background-color: #e0e0e0;
}

.toolbar-select {
  margin: 0 2px;
  height: 36px;
}

.toolbar-select select {
  height: 100%;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  padding: 0 8px;
  cursor: pointer;
  outline: none;
}

.editor-content {
  height: 300px;
  padding: 15px;
  background-color: #fff;
  overflow-y: auto;
  border-radius: 4px !important;
  outline: none !important;
  font-family: Arial, sans-serif;
  font-size: 16px;
  line-height: 1.6;
}

/* 增强的图片调整支持 */
.editor-content img {
  max-width: 100%;
  height: auto;
  resize: both;
  overflow: auto;
  min-width: 50px;
  min-height: 50px;
  cursor: move;
  transition: all 0.2s;
}

.editor-content img:hover {
  box-shadow: 0 0 0 2px rgba(66, 153, 225, 0.5);
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  background-color: #f8f9fa;
  border-top: 1px solid #eee;
  font-size: 14px;
  color: #666;
}

.word-count {
  font-size: 14px;
  color: #666;
}

.upload-progress {
  width: 200px;
}

.progress-bar {
  height: 8px;
  background-color: #eee;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 4px;
}

.progress-inner {
  height: 100%;
  background-color: #4CAF50;
  transition: width 0.3s ease;
}

.upload-tip {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background-color: #4CAF50;
  color: white;
  padding: 10px 15px;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  z-index: 100;
}

.close-tip {
  margin-left: 10px;
  background: none;
  border: none;
  color: white;
  cursor: pointer;
}

.dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.dialog-content {
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 400px;
  max-width: 90%;
}

.dialog-title {
  padding: 15px;
  border-bottom: 1px solid #eee;
  font-size: 18px;
  font-weight: bold;
  display: block;
}

.dialog-body {
  padding: 15px;
}

.dialog-body input {
  width: 100%;
  padding: 8px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}

.dialog-footer {
  padding: 15px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
}

.dialog-btn {
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
  border: none;
}

.cancel {
  background-color: #f0f0f0;
  color: #333;
}

.confirm {
  background-color: #4CAF50;
  color: white;
}

/* 增强的颜色选择器 */
.color-picker {
  position: absolute;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  z-index: 50;
  width: 265px;
  top:50px;
  animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

.color-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8px;
}

.color-item {
  width: 24px;
  height: 24px;
  border-radius: 5px;
  cursor: pointer;
  border: 1px solid #eee;
  transition: all 0.2s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.color-item:hover {
  transform: scale(1.15);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.color-item.active {
  border: 2px solid #fff;
  box-shadow: 0 0 0 2px #3b82f6;
}

.color-preview {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-left: 3px;
  border: 1px solid #ddd;
}

.fullscreen-mode .zmt-editor-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  border-radius: 0;
}

.fullscreen-mode .editor-content {
  height: calc(100vh - 100px);
}

/* 表格单元格调整大小样式 */
.resize-handle {
  position: absolute;
  top: 0;
  right: 0;
  width: 5px;
  height: 100%;
  background-color: #ccc;
  cursor: col-resize;
  opacity: 0;
  transition: opacity 0.2s;
}

td:hover .resize-handle,
th:hover .resize-handle {
  opacity: 1;
}

/* 图片调整控制框样式 */
.image-resize-handler {
  position: absolute;
  border: 1px dashed #3b82f6;
  pointer-events: none;
  box-sizing: border-box;
  z-index: 20;
}

.resize-handle {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #3b82f6;
  border: 1px solid white;
  border-radius: 50%;
  pointer-events: all;
  box-shadow: 0 0 0 1px rgba(59, 130, 246, 0.5);
}

.top-left {
  top: -5px;
  left: -5px;
  cursor: nwse-resize;
}

.top-center {
  top: -5px;
  left: 50%;
  transform: translateX(-50%);
  cursor: ns-resize;
}

.top-right {
  top: -5px;
  right: -5px;
  cursor: nesw-resize;
}

.middle-left {
  top: 50%;
  left: -5px;
  transform: translateY(-50%);
  cursor: ew-resize;
}

.middle-right {
  top: 50%;
  right: -5px;
  transform: translateY(-50%);
  cursor: ew-resize;
}

.bottom-left {
  bottom: -5px;
  left: -5px;
  cursor: nesw-resize;
}

.bottom-center {
  bottom: -5px;
  left: 50%;
  transform: translateX(-50%);
  cursor: ns-resize;
}

.bottom-right {
  bottom: -5px;
  right: -5px;
  cursor: nwse-resize;
}

/* 确保Tailwind工具类正确加载 */
@tailwind utilities;
</style>
